package com.deli.core.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import redis.clients.jedis.Jedis;

import com.deli.core.dao.BrandDAO;
import com.deli.core.pojo.Brand;
import com.deli.core.tools.PageHelper;
import com.deli.core.tools.PageHelper.Page;
import com.github.abel533.entity.Example;

/**
 * 品牌服务类
 * 
 * @author Administrator
 *
 */
@Service("brandService")
@Transactional
public class BrandServiceImpl implements BrandService {

	@Autowired
	private BrandDAO brandDAO;
	@Autowired
	private Jedis jedis;
	
	
	
	@Override
	public List<Brand> findByExample(Brand brand) {
		return brandDAO.select(brand);
	}
	
	public Page findByExample(Brand brand, Integer pageNum,Integer pageSize) {
		PageHelper.startPage(pageNum, pageSize);// 开始分页
		Example example = new Example(Brand.class);
		
		if (brand.getName()==null) {
			brand.setName("");
		}
		if (brand.getIsDisplay()==null) {
			example.createCriteria().andLike("name", "%"+brand.getName()+"%");
		}else{
			example.createCriteria().andLike("name", "%"+brand.getName()+"%").andEqualTo("isDisplay", brand.getIsDisplay());
		}
		List<Brand> brands = brandDAO.selectByExample(example);
		Page endPage = PageHelper.endPage();// 结束分页
		return endPage;
	}

	public Brand findById(Long id) {
		return brandDAO.selectByPrimaryKey(id);
	}

	@Override
	public void updateBrand(Brand brand) {
		//修改的时候将数据上传到redis中
		jedis.hset("brand",String.valueOf(brand.getId()),brand.getName());
		brandDAO.updateByPrimaryKeySelective(brand);
		
	}

	@Override
	public void deleteById(List<Object> ids) {
		Example example = new Example(Brand.class);
		example.createCriteria().andIn("id", ids);
		brandDAO.deleteByExample(example);
		
	}

	@Override
	public Brand findBrandById(Long brandId) {
		return brandDAO.selectByPrimaryKey(brandId);
		
	}

	@Override
	public void doAdd(Brand brand) {
		brandDAO.insert(brand);
		
	}

	@Override
	public String findFormRedis(Long brandId) {
		
		String hget = jedis.hget("brand",String.valueOf(brandId));
		return hget;
	}

	@Override
	public List<Brand> findFormRedis1() {
		Map<String, String> hgetAll = jedis.hgetAll("brand");
		List<Brand> list = new ArrayList<Brand>();
		for (Entry<String, String> entry : hgetAll.entrySet()) {
			Brand brand = new Brand();
			brand.setId(Long.parseLong(entry.getKey()));
			brand.setName(entry.getValue());
			list.add(brand);
		}
		return list;
	}

}
